<template>
	<div class="add-role-container">
		<el-dialog title="添加角色" :visible.sync="showRoleDialog" width="408px" :before-close="cancelRole" custom-class="customerRole-dialog" style="margin-top: 20vh">
			<el-form :model="form" :rules="rules" ref="roleForm" class="role-ruleForm">
				<el-form-item label="" prop="customerRole">
					<el-input v-model="form.customerRole" placeholder="请输入角色名称" maxlength="8" width="372px" height="32px"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="cancelRole" class="cancel-role">取消</el-button>
				<el-button type="primary" @click="saveRole" class="sure-btn">确认添加</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
export default {
	name: '',
	components: {},
	props: {
		showRoleDialog: {
			type: Boolean,
			require: true,
			default: () => false
		},
		roleData: {
			require: true,
			type: Object,
			default: () => {}
		}
	},
	data() {
		const validateRole = (rule, value, callback) => {
			// console.log(value, 'validateRole:', this.roleData);
			let arr = this.roleData.filter(item => item.name === value);
			// console.warn(arr);
			if (arr.length !== 0) {
				return callback(new Error('角色名已存在'));
			} else if (value.trim() === '') {
				return callback(new Error('角色名不能为空!'));
			}
			return callback();
		};
		return {
			form: {
				customerRole: ''
			},
			rules: {
				customerRole: [
					{ required: true, message: '请输入角色名称', trigger: 'blur' },
					{ validator: validateRole, trigger: 'blur' }
				]
			}
		};
	},
	mounted() {
		console.log(this.roleData, 'roleData');
	},
	methods: {
		cancelRole() {
			this.$emit('cancelRole');
			this.$refs['roleForm'].resetFields();
		},
		saveRole() {
			this.$refs['roleForm'].validate(valid => {
				if (valid) {
					this.$emit('saveRole', this.form.customerRole);
					this.$refs['roleForm'].resetFields();
				} else {
					console.error('error submit!!');
					return false;
				}
			});
		}
	}
};
</script>

<style lang="less" scoped>
.add-role-container {
	.el-input {
		height: 32px;
	}
	.dialog-footer {
		.el-button {
			border-radius: 4px;
		}
		.sure-btn {
			// width: 80px;
			background: #6384fe;
			color: #fff;
		}
	}
}
</style>
